package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.domain.AlertRule;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.mapper.AlertRuleMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IAlertDataService;
import com.zzyl.nursing.service.IAlertRuleService;
import com.zzyl.nursing.vo.AlertNotifyVo;
import com.zzyl.nursing.websockerService.WebSocketServer;
import com.zzyl.system.mapper.SysUserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.zzyl.common.constant.CacheConstants.IOT_COUNT_ALERT;
import static com.zzyl.common.constant.CacheConstants.IOT_SILENT_ALERT;

/**
 * 报警规则Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-17
 */
@Service
@Slf4j
public class AlertRuleServiceImpl extends ServiceImpl<AlertRuleMapper, AlertRule> implements IAlertRuleService {
    @Autowired
    private AlertRuleMapper alertRuleMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Value("${alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;

    @Value("${alert.managerRole}")
    private String managerRole;


    @Autowired
    private IAlertDataService alertDataService;

    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 批量保存报警数据
     *
     * @param allUserIds
     * @param rule
     * @param deviceData
     */
    private AlertData insertAlertData(Collection<Long> allUserIds, AlertRule rule, DeviceData deviceData) {
        //新建一个集合存储报警数据集合
        List<AlertData> list = new ArrayList<>();
        //遍历处理人id集合
        for (Long userId : allUserIds) {
            //新建一个报警数据
            AlertData alertData = new AlertData();
            //拷贝
            BeanUtils.copyProperties(deviceData, alertData, "id");
            //赋值
            alertData.setAlertRuleId(rule.getId());
            alertData.setAlertReason(rule.getFunctionId() + rule.getOperator() + rule.getValue() + rule.getDuration() + rule.getAlertEffectivePeriod());
            alertData.setType(rule.getAlertDataType());
            alertData.setStatus(0);
            alertData.setUserId(userId);
            list.add(alertData);
        }
        this.alertDataService.saveBatch(list);
        return list.get(0);
    }

    /**
     * 查询报警规则
     *
     * @param id 报警规则主键
     * @return 报警规则
     */
    @Override
    public AlertRule selectAlertRuleById(Long id) {
        return getById(id);
    }

    /**
     * 查询报警规则列表
     *
     * @param alertRule 报警规则
     * @return 报警规则
     */
    @Override
    public List<AlertRule> selectAlertRuleList(AlertRule alertRule) {
        return alertRuleMapper.selectAlertRuleList(alertRule);
    }

    /**
     * 新增报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int insertAlertRule(AlertRule alertRule) {
        return save(alertRule) ? 1 : 0;
    }

    /**
     * 修改报警规则
     *
     * @param alertRule 报警规则
     * @return 结果
     */
    @Override
    public int updateAlertRule(AlertRule alertRule) {
        return updateById(alertRule) ? 1 : 0;
    }

    /**
     * 批量删除报警规则
     *
     * @param ids 需要删除的报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除报警规则信息
     *
     * @param id 报警规则主键
     * @return 结果
     */
    @Override
    public int deleteAlertRuleById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 过滤数据
     */
    @Override
    public void alertFilter() {
        //查看所有规则
        log.info("查看状态为启动的规则");
        Long count = this.lambdaQuery().eq(AlertRule::getStatus, 1).count();
        //判断是否为空
        if (count <= 0) {
            log.info("没有规则数据");
        }
        //查看所有设备上的数据
        List<List<DeviceData>> values = (List<List<DeviceData>>) redisTemplate.opsForHash().values(CacheConstants.IOT_DEVICE_LAST_DATA);
        //判断设备上报的数据
        if (CollUtil.isEmpty(values)) {
            log.info("设备目前还没有数据");
        }
        //新建一个DeviceDataList集合进行存储数据
        List<DeviceData> dataList = new ArrayList<>();
        for (List<DeviceData> value : values) {
            log.info("设备上报数据填充");
            dataList.addAll(JSONUtil.toList(value.toString(), DeviceData.class));
        }
        //遍历集合
        for (DeviceData deviceData : dataList) {
            //判断设备是不是很久没有上传数据了
            if (LocalDateTime.now().minusMinutes(1).isBefore(deviceData.getAlarmTime())) {
                log.info("执行准备产品下所有物模型和对应设备规则的方法");
                alertFilter(deviceData);
            }
        }
    }

    /**
     * 准备产品下所有物模型和对应设备规则
     *
     * @param deviceData
     */
    private void alertFilter(DeviceData deviceData) {
        //查询设备下对应设备的规则
        List<AlertRule> alertRulesOfSelfList = this.lambdaQuery()
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, deviceData.getIotId())
                .list();
        //查询设备下对应所有设备的规则
        List<AlertRule> alertRuleOfAllList = this.lambdaQuery()
                .eq(AlertRule::getStatus, 1)
                .eq(AlertRule::getProductKey, deviceData.getProductKey())
                .eq(AlertRule::getFunctionId, deviceData.getFunctionId())
                .eq(AlertRule::getIotId, -1)
                .list();
        //添加到一个集合中
        alertRuleOfAllList.addAll(alertRulesOfSelfList);
        if (CollUtil.isEmpty(alertRuleOfAllList)) {
            //返回重新遍历设备上传数据集合
            return;
        }
        //遍历规则集合
        for (AlertRule alertRule : alertRuleOfAllList) {
            //调用检验规则
            alertFilter(alertRule, deviceData);
        }
    }

    /**
     * 检验规则
     *
     * @param alertRule
     */
    private void alertFilter(AlertRule alertRule, DeviceData deviceData) {
        //沉默时间的key
        String silentKey = IOT_SILENT_ALERT + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();
        //统计次数的key
        String aggCountKey = IOT_COUNT_ALERT + deviceData.getIotId() + ":" + deviceData.getFunctionId() + ":" + alertRule.getId();

        //拿到时间生效时间
        String[] alertEffectivePeriod = alertRule.getAlertEffectivePeriod().split("~");
        //拿到生效时间开始时间
        LocalTime startAlertEffectivePeriod = LocalTime.parse(alertEffectivePeriod[0]);
        //拿到生效时间结束时间
        LocalTime endAlertEffectivePeriod = LocalTime.parse(alertEffectivePeriod[1]);
        //拿到当前时间
        LocalTime now = LocalTime.now();
        //判断当前时间是否在规则生效时间中
        if (now.isBefore(startAlertEffectivePeriod) || now.isAfter(endAlertEffectivePeriod)) {
            return;
        }
        //判断数据是否已经达到阈值
        int compare = Double.compare(alertRule.getValue(), Double.parseDouble(deviceData.getDataValue()));
        if (">=".equals(alertRule.getOperator()) && compare > 0 || "<".equals(alertRule.getOperator()) && compare < 0) {
            //没有到达阈值则删除缓存存储的报警次数，重置次数
            redisTemplate.delete(aggCountKey);
            return;
        }
        //拿到redis存储的沉默时间
        Object silentTime = redisTemplate.opsForValue().get(silentKey);
        if (ObjectUtil.isNotEmpty(silentTime)) {
            //如果不为空，则代表已经报警了
            return;
        }
        //获取规则中的阈值
        Integer threshold = alertRule.getDuration();
        //拿到redis中的报警次数进行比对
        Integer value = (Integer) redisTemplate.opsForValue().get(aggCountKey);
        if (!threshold.equals(value)) {
            //不相等则redis报警次数加一次
            redisTemplate.opsForValue().increment(aggCountKey);
            return;
        }
        //相等则删除存储报警次数的缓存
        redisTemplate.delete(aggCountKey);
        //添加沉默周期到redis中，设置过期时间为规则中的值，单位为分钟
        redisTemplate.opsForValue().set(silentKey, "1", alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);
        //新建一个集合
        List<Long> userIds;
        if (alertRule.getAlertDataType().equals(1)) {
            //报警数据类型为1的则不是老人数据，则通报维修员
            userIds = sysUserRoleMapper.selectByRoleName(deviceMaintainerRole);
        } else if (deviceData.getLocationType().equals(1)) {
            //报警数据类型为0则为老人数据，而且绑定位置为固定位置，则先查询床位在查询老人在查询老人和护理人员
            userIds = deviceMapper.selectNursingIdByIotIdWithBed(deviceData.getIotId());
        } else {
            //报警类型为0，而且绑定位置为随身位置
            userIds = deviceMapper.selectNursingIdByIotIdWithElder(deviceData.getIotId());
        }
        //查抄超级管理员的id
        List<Long> managerId = sysUserRoleMapper.selectByRoleName(managerRole);
        //合并userId数据
        userIds.addAll(managerId);
        //去重
        userIds = CollUtil.distinct(userIds);
        //保存报警数据
        AlertData alertData = insertAlertData(userIds, alertRule, deviceData);
        //通过websocker推送消息给前端
        sendWebSocketMessage(alertRule, alertData, userIds);


    }

    /**
     * 调用websocket推送消息
     *
     * @param alertRule
     * @param alertData
     * @param userIds
     */
    private void sendWebSocketMessage(AlertRule alertRule, AlertData alertData, List<Long> userIds) {
        //属性拷贝
        AlertNotifyVo alertNotifyVo = BeanUtil.toBean(alertData, AlertNotifyVo.class);
        //属性赋值
        alertNotifyVo.setAlertDataType(alertData.getType());
        alertNotifyVo.setFunctionName(alertRule.getFunctionName());
        alertNotifyVo.setNotifyType(1);
//        alertNotifyVo.setVoiceNotifyStatus(1);
//        alertNotifyVo.setIsAllConsumer(true);
        //调用websocket推送消息
        webSocketServer.sendMessageToConsumer(alertNotifyVo, userIds);
    }
}
